package com.ljl.service;

import com.ljl.entity.FaceData;
import com.ljl.entity.FaceLocation;
import com.ljl.util.ImageTools;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.math.BigDecimal;
import java.util.List;

/**
 * @author 刘家良
 * @date 2022/10/30 20:32
 * @description /
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FaceDetectService {

    public void resolveImage(File input, List<FaceData> faceDataList, File output) {
        try {
            BufferedImage image = ImageTools.getBufferedImage(input.getAbsolutePath());
            for (FaceData faceData : faceDataList) {
                //处理人脸位置
                FaceLocation location = faceData.getLocation();
                resolveLocation(image, location);
            }
            //输出图片
            ImageTools.saveBufferedImage(image, output.getAbsolutePath());
        }catch (Exception e){
            log.error("无法处理图片[{}]", input.getAbsolutePath());
        }
    }

    public void resolveImage(File input, FaceData faceData, File output) {
        try {
            BufferedImage image = ImageTools.getBufferedImage(input.getAbsolutePath());
            //处理人脸位置
            FaceLocation location = faceData.getLocation();
            resolveLocation(image, location);
            //输出图片
            ImageTools.saveBufferedImage(image, output.getAbsolutePath());
        }catch (Exception e){
            log.error("无法处理图片[{}]", input.getAbsolutePath());
        }
    }

    private void resolveLocation(BufferedImage image, FaceLocation location) {
        //处理人物的位置信息
        int left = BigDecimal.valueOf(location.getLeft()).intValue();
        int top = BigDecimal.valueOf(location.getTop()).intValue();
        int width = BigDecimal.valueOf(location.getWidth()).intValue();
        int height = BigDecimal.valueOf(location.getHeight()).intValue();
        //使用红框，框出人物所在位置
        Graphics graphics = image.createGraphics();
        graphics.setColor(Color.RED);
        graphics.drawRect(left, top, width, height);
        graphics.dispose();
    }

}
